package cn.wmingming.e3mall.item.listener;

import cn.wmingming.e3mall.item.pojo.Item;
import cn.wmingming.e3mall.item.utils.FreeMarkerUtil;
import cn.wmingming.e3mall.manager.service.ItemService;
import cn.wmingming.e3mall.pojo.TbItem;
import cn.wmingming.e3mall.pojo.TbItemDesc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Huangzm
 * @create 2018/06/20 12:51
 * @desc 接收商品添加消息，并生成调用方法静态页面
 * @Modified By:
 **/
public class ItemAddListener implements MessageListener {
    @Autowired
    private ItemService itemService;
    @Autowired
    private  FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${FREEMARKER_PATH}")
    private String path;
    @Override
    public void onMessage(Message message) {
        try {
            TextMessage id = (TextMessage) message;
            Thread.sleep(100);
            TbItem tbItem = itemService.getItemById(Long.valueOf(id.getText()));
            Item item = new Item(tbItem);
            item.setId(Long.valueOf(id.getText()));
            TbItemDesc itemDesc = itemService.getItemDesc(Long.valueOf(id.getText()));
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("item",item);
            map.put("itemDesc",itemDesc);
            //生成文件的路径和名称
            String outputFile = path + id.getText()+ ".html";
            //生成静态页面
            FreeMarkerUtil.generateStaticHtml(map,freeMarkerConfigurer,outputFile,"item.ftl");
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
